#!/usr/bin/env python3
"""
===============================================================================
 SOVEREIGN BUILDER ORCHESTRATOR (v8.0 "Universe")
 Author: Thomas B. Sweet
 Description: Bootstraps environment and prepares the AI AUDIT Context.
===============================================================================
"""

import os
import sys
import subprocess
import platform
import venv

# --- CONFIGURATION ---
BUILDER_VENV = "launcher_venv"
REQUIRED_PACKAGES = ["pyyaml", "google-generativeai", "requests"]
MASTER_CONFIG = "MASTER.yaml"
DEFAULT_CONFIG = "DEFAULT.yaml"

def log(msg):
    print(f"\033[1;36m[ORCHESTRATOR]\033[0m {msg}")

def bootstrap_venv():
    if platform.system() == "Windows":
        python_bin = os.path.join(BUILDER_VENV, "Scripts", "python.exe")
        pip_bin = os.path.join(BUILDER_VENV, "Scripts", "pip.exe")
    else:
        python_bin = os.path.join(BUILDER_VENV, "bin", "python")
        pip_bin = os.path.join(BUILDER_VENV, "bin", "pip")

    if not os.path.exists(BUILDER_VENV):
        log(f"Creating isolated environment: {BUILDER_VENV}...")
        venv.create(BUILDER_VENV, with_pip=True)

    try:
        subprocess.check_call([python_bin, "-c", "import yaml; import google.generativeai"],
                              stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        log("Installing builder dependencies...")
        subprocess.check_call([pip_bin, "install"] + REQUIRED_PACKAGES)

    return python_bin

def read_config(python_bin, config_file):
    py_script = f"""
import yaml
try:
    with open('{config_file}', 'r') as f:
        data = yaml.safe_load(f)
        print(f"LOADED: {{data['meta']['project_name']}} v{{data['meta']['version']}}")
        print(f"CODENAME: {{data['meta']['codename']}}")
except Exception as e:
    print(f"FAIL: {{e}}")
"""
    result = subprocess.run([python_bin, "-c", py_script], capture_output=True, text=True)
    print(result.stdout.strip())

def main():
    log("Initializing Sovereign Builder v8.0...")

    python_exec = bootstrap_venv()
    target_config = MASTER_CONFIG if os.path.exists(MASTER_CONFIG) else DEFAULT_CONFIG
    log(f"Target Configuration: {target_config}")
    read_config(python_exec, target_config)

    print("\n" + "="*60)
    print(" READY FOR AI AUDIT & PROBE")
    print("="*60)
    print(f"1. Please ensure 'Gemini_API.key' is in the root folder.")
    print(f"2. In the NEXT session, upload 'MASTER.yaml', 'launcher.py' and 'TREE.txt'.")
    print("-" * 60)
    print("PROMPT FOR NEW SESSION:")
    print("I am building FurryOS v8.0 'Sovereign Universe'. Attached is the 'MASTER.yaml'.")
    print("Please act as the Sovereign Code Generator.")
    print("1. Read the YAML and TREE to understand the Universe Architecture.")
    print("2. STOP and ASK me 3-5 clarifying questions about Hardware/Accessibility")
    print("   (e.g., 'Targeting specific NVIDIA drivers?', 'Preferred Voice for Reader?').")
    print("3. WAIT for my answers.")
    print("4. THEN generate the C++ Source Code (`src/*.cpp`) and `compile_now.sh`.")
    print("="*60)

if __name__ == "__main__":
    main()
